package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper mapper;


    public void delete(Long id) {

        //删除关系
        mapper.deleteRelation(id);

        mapper.deleteByPrimaryKey(id);
    }

    public void save(Role entity) {
        mapper.insert(entity);

        //维护关系
        List<Permission> permissions = entity.getPermissions();
        if (permissions != null && permissions.size() > 0) {
            for (Permission permission : permissions) {
                mapper.saveRelation(entity.getId(),permission.getId());
            }
        }

    }

    public void update(Role entity) {
        //先删除关系
        mapper.deleteRelation(entity.getId());

        mapper.updateByPrimaryKey(entity);

        //再维护关系
        List<Permission> permissions = entity.getPermissions();
        if (permissions != null && permissions.size() > 0) {
            for (Permission permission : permissions) {
                mapper.saveRelation(entity.getId(),permission.getId());
            }
        }
    }

    public Role get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<?> list() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int total = mapper.queryForCount(qo);
        if (total == 0) {
            return new PageResult();
        }
        List<Role> list = mapper.queryForList(qo);
        return new PageResult(total,list);
    }

    public List<Long> getRoleIdsByEmployeeId(Long id) {
        return mapper.getRoleIdsByEmployeeId(id);
    }

    @Override
    public List<String> getRoleSnByEmployeeId(Long id) {
        return mapper.getRoleSnByEmployeeId(id);
    }
}
